<template>
  <div>
    <div class="common_title">
        <span style="font-size:20px;font-weight:bold">用户管理</span>
      </div>
    <!-- 查询框 -->
    <div class="query_bg">
        <span class="query_bg_username">
          <el-input placeholder="用户ID/用户名" v-model="input" size="small" style="width:200px"> </el-input>
        </span>
        <span class="query_bg_button" style="margin-left:20px">
          <el-button type="goon" icon="el-icon-search" size="small" @click="findByName()">查询</el-button>
        </span>

        <span class="query_bg_addData" style="margin-left:20px">
            <el-button type="goon" icon="el-icon-plus" @click="addAcountClick" size="small">新增</el-button>
        </span>
        <div class="grid-content bg-purple-light"></div>
    </div>
    <!-- <hr style='border:0.5px inset #FAFAFA;'> -->
    <!-- 数据列表框 -->
    <div  class="dataList_bg">
      <div class="dataList">
        <el-table ref="multipleTable" size="small" :data="tableData" tooltip-effect="dark" style="width: 100%" :default-sort = "{prop: 'id', order: 'descending'}">
          <!-- <el-table-column type="selection" width="55">
          </el-table-column> -->
          <!-- <el-table-column prop="id" label="序号" sortable header-align="center" align="center"> </el-table-column> -->
          <el-table-column header-align="center" sortable align="center" width="80" label="序号">
            <template slot-scope="scope">
              <span>{{(page - 1) * perPage + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" header-align="center" align="center" width="100" label="用户名"></el-table-column>
          <el-table-column prop="userPosition" header-align="center" align="center" label="职务"></el-table-column>
          <el-table-column prop="depts" header-align="center" align="center" label="所属部门">
            <template slot-scope="scope">
              <span v-for="(item,index) in scope.row.depts" :key="index">{{item.deptName}}&ensp;</span>
            </template>
          </el-table-column>
          <el-table-column prop="roles" header-align="center" align="center" label="角色">
            <template slot-scope="scope">
              <span v-for="(item,index) in scope.row.roles" :key="index">{{item.roleName}}&ensp;</span>
            </template>
          </el-table-column>
          <el-table-column prop="userAge" header-align="center" align="center" width="50" label="年龄"></el-table-column>
          <el-table-column prop="userGender" header-align="center" align="center" width="50" label="性别"></el-table-column>
          <el-table-column prop="userTel" header-align="center" align="center" label="手机"></el-table-column>
          <el-table-column prop="userEmail" header-align="center" align="center" label="邮箱"></el-table-column>
          <el-table-column prop="userAdd" header-align="center" align="center" label="地址"></el-table-column>
          <el-table-column prop="" label="操作" width="300" show-overflow-tooltip header-align="center" align="center">
              <!-- <el-button round size="mini">查看</el-button> -->
              <template slot-scope="scope">
                <el-button round size="mini" @click="editAcountClick(scope.row)">编辑</el-button>
                <el-button type="danger" round size="mini" @click="deleteAcountClick(scope.row)">删除</el-button>
              </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="block" style="width:100%;text-align:right;margin-top:10px">
          <el-pagination @size-change="handleperPageChange" @current-change="refreshPageRequest" :current-page="page" :page-sizes="[10, 20, 50]" :page-size="perPage"  layout="total, sizes, prev, pager, next, jumper" :total="total"> 
          </el-pagination>
      </div>
    </div>
    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="50%" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="80px" :rules="dataFormRules" ref="dataForm" :size="size" label-position="right">
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="账号" prop="userAcc">
              <el-input v-model="dataForm.userAcc" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="电话" prop="userTel">
              <el-input v-model="dataForm.userTel" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="密码" prop="userPwd">
              <el-input v-model="dataForm.userPwd" type="password" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="邮箱" prop="userEmail">
              <el-input v-model="dataForm.userEmail" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="dataForm.userName" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="用户昵称" prop="userNickname">
              <el-input v-model="dataForm.userNickname" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="地址" prop="userAdd">
              <el-input v-model="dataForm.userAdd" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="年龄" prop="userAge">
              <el-input v-model="dataForm.userAge" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="职称" prop="userPosition">
              <el-input v-model="dataForm.userPosition" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="性别" prop="userGender">
              <el-input v-model="dataForm.userGender" auto-complete="off"></el-input>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="备注" prop="userNote">
              <el-input v-model="dataForm.userNote" auto-complete="off"></el-input>
            </el-form-item>
          </div>
          <div style="flex:1"></div>
        </div>
        <div style="display:flex;margin-left:-25px" v-if="!operation">
          <div style="flex:1">
            <el-form-item label="已属部门" prop="depts">
              <div style="display:flex">
                <el-input
                  v-for="(item,index) in dataForm.depts"
                  v-model="item.deptName"
                  :key="index"
                  auto-complete="off"
                  :disabled="true"
                  style="flex:1;margin-right:5px"
                ></el-input>
              </div>
            </el-form-item>
          </div>
          <div style="flex:1">
            <el-form-item label="已有角色" prop="roles">
              <div style="display:flex">
                <el-input
                  v-for="(item,index) in dataForm.roles"
                  v-model="item.roleName"
                  :key="index"
                  auto-complete="off"
                  :disabled="true"
                  style="flex:1;margin-right:5px"
                ></el-input>
              </div>
            </el-form-item>
          </div>
        </div>
        <div style="display:flex;margin-left:-25px">
          <div style="flex:1">
            <el-form-item label="部门" prop="deptIds">
              <!-- <span style="margin-left:10%">部门&ensp;</span> -->
              <el-select v-model="dataForm.deptIds" multiple placeholder="请选择" style="width:79%">
                <el-option v-for="item in depts" :key="item.deptId" :label="item.deptName" :value="item.deptId"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="flex:1" v-if="!operation">
            <el-form-item label="角色" prop="roleIds1">
              <el-select v-model="dataForm.roleIds" multiple placeholder="请选择" style="width:79%">
                <el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
              </el-select>
            </el-form-item> 
          </div>
          <div style="flex:1" v-else>
            <el-form-item label="角色" prop="roleIds">
              <el-select v-model="dataForm.roleIds" multiple placeholder="请选择" style="width:79%">
                <el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId"></el-option>
              </el-select>
            </el-form-item> 
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click="resetForm('dataForm')">取消</el-button>
        <el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading" style="background-color: #37508D;">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  data() {
      return {
        size: "small",
        value: '',
        input: '',
        input1: '',
        page: 1, //当前页
        perPage: 10, //每页多少条数据
        total: 0, //总共多少条数据
        startUseValue:true,
        tableData: [],
        multipleSelection: [],
        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        depts: [],
        roles: [],
        editLoading: false,
        dataFormRules: {
          userAcc: [{ required: true, message: "请输入账号", trigger: "blur" }],
          userPwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
          userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
          userTel: [{ required: true, message: "请输入电话", trigger: "blur" }],
          userEmail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
          roleIds: [{ required: true, message: "请至少选择一个角色类型", trigger: "change" }],
          roleIds1: [{ required: false, message: "请至少选择一个角色类型", trigger: "change" }],
        },
        // 新增编辑界面数据
        dataForm: {
          userAcc: "",
          userTel: "",
          userPwd: "",
          userEmail: "",
          userName: "",
          userNickname: "",
          userAdd: "",
          userAge: "",
          userPosition: "",
          userGender: "",
          userNote: "",
          deptIds: [],
          roleIds: []
        }
      }
    },
    methods: {
      // 获取用户总量
      getCount: function() {
        this.$api.user.count().then(res => {
          this.total = res.data.totalSize;
        });
      },
      // 获取分页数据
      findPage: function() {
        this.$api.user.findByPage(this.page,this.perPage).then(res => {
            this.tableData = res.data.userlist;
            console.log(res);
          })
          .then();
      },
      // 获取部门列表
      findDeptTree: function() {
        this.$api.dept.findAll().then(res => {
          this.depts = res.data;
          console.log(this.depts);
        });
      },
      // 获取角色列表
      findUserRoles: function() {
        this.$api.role.findAll().then(res => {
          // 加载角色集合
          this.roles = res.data;
          console.log(this.roles);
        });
      },
      // 按用户名查询
      findByName: function() {
        if(this.input){
          this.$api.user.findByName(this.input).then(res => {
          this.tableData = res.data;
          this.total = this.tableData.length;
          })
        } else{
          this.findPage();
          this.getCount();
        }
      },
      // 换页刷新
      refreshPageRequest: function(pageNum) {
        this.page = pageNum;
        this.$api.user.findByPage(this.page,this.perPage).then(res => {
          this.tableData = res.data.userlist;
          console.log(this.tableData);
        });
      },
      // 每页显示条数改变
      handleperPageChange(val) {
        console.log(val);
        this.perPage = val
        this.$api.user.findByPage(this.page,this.perPage).then(res => {
          this.tableData = res.data.userlist;
          console.log(this.tableData);
        });
      },
      // 新增
      addAcountClick() {
        this.dialogVisible = true;
        this.operation = true;
        this.dataForm = {
          userAcc: "",
          userTel: "",
          userPwd: "",
          userEmail: "",
          userName: "",
          userNickname: "",
          userAdd: "",
          userAge: "",
          userPosition: "",
          userGender: "",
          userNote: "",
          deptIds: [],
          roleIds: []
        };
      },
      // 编辑
      editAcountClick(params) {
        console.log(params);
        let hasdepts1 = { hasdepts: [] };
        let hasroles1 = { hasroles: [] };
        for (let i = 0; i < params.depts.length; i++) {
          hasdepts1.hasdepts.push(params.depts[i].deptId);
        }
        for (let i = 0; i < params.roles.length; i++) {
          hasroles1.hasroles.push(params.roles[i].roleId);
        }
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params, hasdepts1, hasroles1);
        
        console.log(this.dataForm);
      },
       resetForm(formName) {
        this.$refs[formName].resetFields();
        this.dialogVisible = false
      },
      // 表单提交
      submitForm: function() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              this.$refs["dataForm"].resetFields();
              if (this.operation) {
                this.$api.user.addUser(this.dataForm).then(res => {
                  this.editLoading = false;
                  if (res.code == 200) {
                    this.$message({ message: "操作成功", type: "success" });
                    this.dialogVisible = false;
                    console.log(res.data);
                  } else {
                    this.$message({
                      message: "操作失败, " + res.msg,
                      type: "error"
                    });
                  }
                  this.$refs[this.dataForm].resetFields();
                  this.findPage();
                  this.getCount();
                });
              } else {
                this.$api.user.updateUser(this.dataForm).then(res => {
                  console.log;
                  this.editLoading = false;
                  if (res.code == 200) {
                    this.$message({ message: "操作成功", type: "success" });
                    this.dialogVisible = false;
                    this.$refs["dataForm"].resetFields();
                    console.log(res.data);
                  } else {
                    this.$message({
                      message: "操作失败, " + res.msg,
                      type: "error"
                    });
                  }
                  this.findPage();
                  this.getCount();
                });
              }
            });
          }
        });
      },
      // 删除
      deleteAcountClick(data) {
        console.log(data.userId);
        this.$confirm('确定要删除这个用户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.user.batchDelete(data.userId).then(res => {
            console.log(res);
            this.page = 1
            this.findPage();
            this.getCount();
          }).then();
        }).catch(() => {});
      }
        
    },
    mounted() {
      this.getCount();
      this.findPage();
      // this.initColumns();
      this.findDeptTree();
      this.findUserRoles();
    }
}
</script>

<style lang="less" scoped>
.common_title {
    margin-top: 20px;
}
.query_bg {
    height: 80px;
    line-height: 80px;
    margin-top: 10px;
    //   background-color: hotpink;

    .el-button--goon {
      color: #FFF;
      background-color: #37508D;
      border-color: #37508D;
    }

    .el-input, .el-select {
        width: 140px;
    }
}

.dataList_bg {
      height: 90%;
      margin-top: 5px;
    //   background-color: lawngreen;
}

</style>
